package com.ybbase.framework.service.system.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ybbase.framework.base.model.TreeModel;
import com.ybbase.framework.base.service.TreeService;
import com.ybbase.framework.mapper.system.OrganPostMapper;
import com.ybbase.framework.mapper.system.OrganUserMapper;
import com.ybbase.framework.mapper.system.OrganizationMapper;
import com.ybbase.framework.mapper.system.PostMapper;
import com.ybbase.framework.model.po.system.*;
import com.ybbase.framework.model.vo.organ.OrganTreeVO;
import com.ybbase.framework.service.system.OrganizationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.parameters.P;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 系统机构 服务实现类
 * </p>
 *
 * @author cg
 * @since 2019-11-25
 */
@Service
public class OrganizationServiceImpl extends ServiceImpl<OrganizationMapper, Organization> implements OrganizationService {


    @Autowired
    OrganizationMapper organizationMapper;
    @Autowired
    TreeService treeService;
    @Autowired
    OrganPostMapper organPostMapper;
    @Autowired
    PostMapper postMapper;
    @Autowired
    OrganUserMapper organUserMapper;

    /**
     * 根据用户查询组织机构列表
     * @param userId 用户编码
     * @return List<Organization>
     * @author cg
     * @date 2019-11-26 13:54
     * @since cloud2.0
     */
    @Override
    public List<Organization> getOrgListByUserId(Integer userId) {
        return organizationMapper.getOrgListByUserId(userId);
    }

    /**
     * 根据用户编码获取企业在机构里面的组织机构编码
     *
     * @param userId 用户编码
     * @return Organization
     * @author cg
     * @date 2019-11-28 14:06
     * @since cloud2.0
     */
    @Override
    public Organization getOrganCompanyByUserId(Integer userId) {
        Organization companyOrgan = new Organization();
        List<Organization> organizationList =  this.getOrgListByUserId(userId);
        QueryWrapper<Organization> organizationQueryWrapper = new QueryWrapper<>();
        organizationQueryWrapper.lambda().eq(Organization::getType, 2);
        organizationQueryWrapper.lambda().eq(Organization::getDelFlag, 0);
        List<Organization> companyOrgans = this.list(organizationQueryWrapper);
        if (organizationList!=null&&organizationList.size()>0){
            if(companyOrgans!=null && companyOrgans.size()>0){
                for(Organization o:companyOrgans){
                    if(organizationList.get(0).getPath().indexOf(o.getId())!=-1){
                        companyOrgan = o;
                        break;
                    }
                }
            }
        }
        return companyOrgan;
    }

    /**
     * 机构树
     * @param
     * @return
     * @author jzw
     * @date 2019/12/4 9:10
     * @since cloud2.0
     */
    @Override
    public List<OrganTreeVO> getOrganTree(List<Organization> list) {
        List<OrganTreeVO> firstList = new ArrayList<>();
        List<OrganTreeVO> sourseList =  new ArrayList<>();
        for (Organization organization:list) {
            OrganTreeVO organTreeVO = assemble(organization);
            if (organization.getParentId() == 0) {
                firstList.add(organTreeVO);
            }
            sourseList.add(organTreeVO);
        }
        treeService.sortOrganTree(firstList, sourseList);
        return firstList;
    }



    /**
     * 填充实体
     * @param
     * @return
     * @author jzw
     * @date 2019/12/4 9:23
     * @since cloud2.0
     */
    private OrganTreeVO assemble(Organization organization) {
        OrganTreeVO organTreeVO = new OrganTreeVO();
        organTreeVO.setId(organization.getId());
        organTreeVO.setTitle(organization.getName());
        organTreeVO.setParentId(organization.getParentId());
        return organTreeVO;
    }

    /**
     * 保存机构和岗位的关系
     * @param organId 机构编码
     * @param postIds 岗位编码
     * @author jzw
     * @date 2019/12/4 16:37
     * @since cloud2.0
     */
    @Override
    public void saveOrganPost(Integer organId, List<Post> postIds) {

        /**
         *  重新增加机构岗位信息
         * */
        if (postIds!= null && postIds.size()>0) {
            for (Post post: postIds) {
                /**
                 *  查询该机构已存在的岗位（已存在不在重复增加）
                 * */
                QueryWrapper<OrganPost> queryWrapper = new QueryWrapper<>();
                queryWrapper.lambda().eq(OrganPost::getOrganId, organId);
                queryWrapper.lambda().eq(OrganPost::getPostId, post.getId());
                int count = organPostMapper.selectCount(queryWrapper);
                /**
                 *  增加机构和岗位的对照关系
                 * */
                if (count == 0){
                    OrganPost organPost = new OrganPost();
                    organPost.setOrganId(organId);
                    organPost.setPostId(post.getId());
                    organPostMapper.insert(organPost);
                }
            }
        }
    }

    /**
     * 获取指定机构下的岗位信息
     * @param
     * @return
     * @author jzw
     * @date 2019/12/4 17:52
     * @since cloud2.0
     */
    @Override
    public List<Post> getOrganPostList(Integer organId) {
        return postMapper.getOrganPostList(organId);
    }


    /**
     * 删除指定机构下的岗位关系
     * @param organId
     * @param postIds
     * @author jzw
     * @date 2019/12/4 17:23
     * @since cloud2.0
     */
    @Override
    public void deleteOrganPost(Integer organId, List<Post> postIds) {
        if (postIds!=null && postIds.size()>0) {
            for (Post post: postIds) {
                QueryWrapper<OrganPost> organPostQueryWrapper = new QueryWrapper<>();
                organPostQueryWrapper.lambda().eq(OrganPost::getOrganId, organId);
                organPostQueryWrapper.lambda().eq(OrganPost::getPostId, post.getId());
                organPostMapper.delete(organPostQueryWrapper);
            }
        }
    }

    /**
     * 根据路径查询下钻数据
     * @param
     * @return
     * @author cg
     * @date 2019-12-05 20:59
     * @since cloud2.0
     */
    @Override
    public List<Organization> getOrgListByPath(String path) throws Exception {
        return organizationMapper.getOrgListByPath(path);
    }


    @Override
    public void saveRole(int organizationId,int roleId){
        organizationMapper.saveRole(organizationId,roleId);
    }

    @Override
    public Boolean getOrganRoleById(int organizationId){
        return organizationMapper.getOrganRoleById(organizationId).size() > 0;
    }
    @Override
    public Page<Role> getOrganRoleListById(int organizationId, int currPage, int pageSize){
        //查询全部数据
        List<Role> roles = organizationMapper.getOrganRoleById(organizationId);
        Page<Role> page = new Page<>(currPage,pageSize,roles.size());
        //从第几条数据开始
        int firstIndex = (currPage - 1) * pageSize;
        int pages = roles.size()/pageSize;
        page.setPages(pages);
        //到第几条数据结束
        int lastIndex = currPage * pageSize;
        if (roles.size()<lastIndex){
            lastIndex = roles.size();
        }
        /**
         * 直接在list中截取
         * */
        return page.setRecords(roles.subList(firstIndex, lastIndex));
    }

    @Override
    public void removeRoleById (String organizationId,String roleId){
        String [] roles = roleId.split(",");
        for (int i = 0; i < roles.length; i++) {
            organizationMapper.removeRoleById(Integer.parseInt(organizationId), Integer.parseInt(roles[i]));
        }
    }

    /**
     * 保存或者更新组织机构信息
     *
     * @param organization 组织机构数据
     * @return
     * @author cg
     * @date 2020-01-06 00:22
     * @since cloud2.0
     */
    @Override
    public void saveOrUpdateOrganization(Organization organization) {
        if(organization!=null){
            Organization oldOrgan = new Organization();
            String path = "";
            if (organization.getParentId()!=null&&organization.getParentId()!=0){
                oldOrgan = organizationMapper.selectById(organization.getParentId());
                organization.setParentName(oldOrgan.getName());
                path = oldOrgan.getPath();
            }else{
                organization.setParentId(0);
            }
            if(organization.getId()!=null&&organization.getId()!=0){
                organization.setPath(path+organization.getId()+"|");
                organizationMapper.updateById(organization);
            }else {

                organizationMapper.insert(organization);
                organization.setPath(path+organization.getId()+"|");
                organizationMapper.updateById(organization);
            }
        }
    }

    /**
     * 根据组织机构ID获取组织机构用户信息
     *
     * @param id organId
     * @return
     * @author cg
     * @date 2020-01-06 01:24
     * @since cloud2.0
     */
    @Override
    public List<OrganUser> getOrganUserByOrgId(String id) {
        QueryWrapper<OrganUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(OrganUser::getOrgId, Integer.parseInt(id));
        return organUserMapper.selectList(queryWrapper);
    }

    /**
     * 根据类型和id集合进行查询
     * @param organIds
     * @return
     * @author cg
     * @date 2020-01-27 23:09
     * @since cloud2.0
     */
    @Override
    public List<Organization> getOrgListQuery(String[] organIds, int type) {
        return organizationMapper.getOrgListQuery(organIds,type);
    }

}


